package com.tiyo.wechat.service.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiyo.common.exception.BusinessException;
import com.tiyo.common.utils.StringUtils;
import com.tiyo.wechat.mapper.WeChatConfigMapper;
import com.tiyo.wechat.mapper.domain.WeChatConfigEntity;
import com.tiyo.wechat.service.WechatService;
import com.tiyo.wechat.service.model.WechatConfigModel;
import com.tiyo.wechat.util.WechatUtil;
import com.tiyo.wechat.util.WechatUtil.AccessTokenResponse;
import com.tiyo.wechat.util.WechatUtil.JSApiResponse;
import com.tiyo.wechat.util.WechatUtil.MessageResponse;
import com.tiyo.wechat.util.WechatUtil.UserOpenIdResponse;
@Service
public class WechatServiceImpl implements WechatService {
	private static final Logger log = LoggerFactory.getLogger(WechatServiceImpl.class);
	@Autowired
	WeChatConfigMapper weChatConfigMapper;
	/**
	 * 
	 *  Description:获取微信公众号信息
	 *  @author yangb  
	 *  @date 2022年7月26日 下午4:34:20 
	 *  @param appid
	 *  @param secret
	 *  @return
	 */
	@Override
	@Transactional
	public WechatConfigModel getToken(String appid,String secret) {
		WechatConfigModel configModel = new WechatConfigModel();
		Date currentTime = new Date();
		QueryWrapper<WeChatConfigEntity> configQueryWarrper= new QueryWrapper<WeChatConfigEntity>();
		configQueryWarrper.eq("status", 1);
		WeChatConfigEntity configEntiy=weChatConfigMapper.selectOne(configQueryWarrper);
		if(StringUtils.isNull(configEntiy)) {
			log.error("微信公众号配置不存在。。。。");
			throw new BusinessException("微信公众号配置不存在");
		} else {
			if(!configEntiy.getAppid().equals(appid) || !configEntiy.getAppsecret().equals(secret)) {
				log.error("通过appid【{}】secret【{}】获取微信公众号token失败，系统配置appid【{}】secret【{}】", appid,secret,configEntiy.getAppid(),configEntiy.getAppsecret());
				throw new BusinessException("微信公众号参数错误");
			}
			if(StringUtils.isEmpty(configEntiy.getAccessToken()) || StringUtils.isNull(configEntiy.getTokenRefreshTime())){
				refreshToken(configEntiy);
				refreshJSAPITikcet(configEntiy);
			} else if((currentTime.getTime()-configEntiy.getTokenRefreshTime().getTime())/ 1000 / 60>=100) {
				refreshToken(configEntiy);
				refreshJSAPITikcet(configEntiy);
			} else {
				log.info("微信公众号Token过期时间为【{}】未过期",configEntiy.getTokenRefreshTime());
				if(StringUtils.isEmpty(configEntiy.getJsapiTicket()) || StringUtils.isNull(configEntiy.getTicketRefreshTime())) {
					refreshJSAPITikcet(configEntiy);
				} else if((currentTime.getTime()-configEntiy.getTicketRefreshTime().getTime())/ 1000 / 60>=100) {
					refreshJSAPITikcet(configEntiy);
				}
			}
			log.info("微信公众号配置：{}",JSONObject.toJSONString(configEntiy));
		} 
		configModel.setAppId(configEntiy.getAppid());
		configModel.setAccessToken(configEntiy.getAccessToken());
		configModel.setJsapiTicket(configEntiy.getJsapiTicket());
		configModel.setTokenRefreshTime(configEntiy.getTokenRefreshTime());
		configModel.setTicketRefreshTime(configEntiy.getTicketRefreshTime());
		return configModel;
	}
	
	@Override
	public UserOpenIdResponse auth2(String appid, String secret, String code) {
		QueryWrapper<WeChatConfigEntity> configQueryWarrper= new QueryWrapper<WeChatConfigEntity>();
		configQueryWarrper.eq("status", 1);
		WeChatConfigEntity configEntiy=weChatConfigMapper.selectOne(configQueryWarrper);
		if(StringUtils.isNull(configEntiy)) {
			log.error("微信公众号配置不存在。。。。");
			throw new BusinessException("微信公众号配置不存在");
		} else {
			if(!configEntiy.getAppid().equals(appid) || !configEntiy.getAppsecret().equals(secret)) {
				log.error("通过appid【{}】secret【{}】获取微信公众号token失败，系统配置appid【{}】secret【{}】", appid,secret,configEntiy.getAppid(),configEntiy.getAppsecret());
				throw new BusinessException("微信公众号参数错误");
			}
			return WechatUtil.getUserOpenId(configEntiy.getAppid(),configEntiy.getAppsecret(), code);
		}
	}

	@Override
	public MessageResponse sendMsg(String token, JSONObject message) {
		return WechatUtil.sendMsg(token, message);
	}

	private WeChatConfigEntity refreshToken(WeChatConfigEntity configEntiy) {
		Date currentTime = new Date();
		AccessTokenResponse resonse= WechatUtil.getToken(configEntiy.getAppid(), configEntiy.getAppsecret());
		if("0".equals(resonse.getErrcode())) {
			configEntiy.setAccessToken(resonse.getAccess_token());
			configEntiy.setTokenRefreshTime(currentTime);
			weChatConfigMapper.updateById(configEntiy);
		} else {
			log.error("获取微信公众号TOKEN失败:{}", resonse.getErrmsg());
		}
		return configEntiy;
	}
	private WeChatConfigEntity refreshJSAPITikcet(WeChatConfigEntity configEntiy) {
		Date currentTime = new Date();
		JSApiResponse resonse= WechatUtil.getJsapiTicket(configEntiy.getAccessToken());
		if("0".equals(resonse.getErrcode())) {
			configEntiy.setJsapiTicket(resonse.getTicket());
			configEntiy.setTicketRefreshTime(currentTime);;
			weChatConfigMapper.updateById(configEntiy);
		} else {
			log.error("获取微信公众号JSAPITicket失败:{}", resonse.getErrmsg());
		}
		return configEntiy;
	}
}
